package com.atguigu.gulimail.controller;

import com.atguigu.gulimail.service.CartService;
import com.atguigu.gulimail.vo.Cart;
import com.atguigu.gulimail.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {

    @Autowired
    CartService cartService;


    @ResponseBody
    @GetMapping("/cartItem")
    public List<CartItem> getCartItem(){
        return cartService.getCartItem();

    }



    @RequestMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId")String skuId){
        cartService.deleteItem(skuId);
        return  "redirect:http://cart.gulimail.com/cart.html";
    }



    @RequestMapping("/changeNum")
    public String changeNum(@RequestParam("skuId")String skuId,@RequestParam("num") Integer num){

        cartService.changeNum(skuId,num);

        return  "redirect:http://cart.gulimail.com/cart.html";
    }


    @RequestMapping("/checkItem")
    public String checkItem(@RequestParam("skuId")String skuId,@RequestParam("check") Integer check){

        cartService.checkItem(skuId,check);
        return "redirect:http://cart.gulimail.com/cart.html";
    }


    @RequestMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, InterruptedException {

        //进入到购物车页面。
       Cart cart= cartService.cartListPage();

        model.addAttribute("cart", cart);

        return "cartList";
    }

    /**
     * 防止页面重复刷新。使用重定向功能。
     */
    @RequestMapping("/addToCart")
    public String addToCart(@RequestParam("skuId")Long skuId,
                            @RequestParam("skuNum")Integer skuNum,
                            RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {

        CartItem cartItem=cartService.addToCart(skuId,skuNum);

        redirectAttributes.addAttribute("skuId",skuId);


        return "redirect:http://cart.gulimail.com/addToCartSuccess.html";
    }


    @RequestMapping("/addToCartSuccess.html")
    public String addToCartSuccess(@RequestParam("skuId") Long SkuId,Model model){
       CartItem cartItem= cartService.addToCartSuccess(SkuId);

       model.addAttribute("item",cartItem);

       return "success";

    }



}
